package cn.wit.summit.chwan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.convenientbanner.ConvenientBanner;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameLibraryTopAdapter;
import cn.wit.summit.chwan.adapters.GameLibraryTwoAdapter;
import cn.wit.summit.chwan.interfaces.ScrollHeightListener;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/7.
 */

public class GameLibraryTwoFragment extends BaseFragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private GameLibraryV3Response.PlayTypeInfoBean play_type_info;

    private GridLayoutManager gridLayoutManager;
    private GameLibraryTwoAdapter adapter;
    private List<GameLibraryTwoAdapter.ViewBean> viewBeans = new ArrayList<>();
    private int pn = 1;

    private JumpBaseBean bottomBanner;
    private List<JumpBaseBean> banner;
    private ScrollHeightListener listener;
    private int totalDy = 0;
    private ViewPager viewPager;
    private GameLibraryTopAdapter mAdapter;
    private LinearLayoutManager layoutManager;
    private JumpBaseBean banner_ad;

    public static GameLibraryTwoFragment newInstance(ScrollHeightListener listener, GameLibraryTopAdapter mAdapter, ViewPager viewPager, List<JumpBaseBean> banner, GameLibraryV3Response.PlayTypeInfoBean play_type_info, JumpBaseBean banner_ad) {
        GameLibraryTwoFragment temp = new GameLibraryTwoFragment();
        temp.play_type_info = play_type_info;
        temp.banner = banner;
        temp.listener = listener;
        temp.viewPager = viewPager;
        temp.mAdapter = mAdapter;
        temp.banner_ad = banner_ad;
        return temp;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_library_two, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        listener.OnScroll(1, totalDy, 0);

//        gridLayoutManager = new GridLayoutManager(getActivity(), 3) {
//            @Override
//            public boolean canScrollVertically() {
//                return true;
//            }
//        };
//        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//                if (adapter.getItemViewType(position)==GameLibraryTwoAdapter.ViewType.TYPE_ITEM.ordinal()) {
//                    return 1;
//                } else {
//                    return gridLayoutManager.getSpanCount();
//                }
//            }
//        });
//        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);

        layoutManager = new LinearLayoutManager(getContext());

        adapter = new GameLibraryTwoAdapter(getActivity(), viewBeans, viewPager, mAdapter);
        recyclerView.setLayoutManager(layoutManager);
//        int height = (int) getActivity().getResources().getDimension(R.dimen.wdp20);
//        recyclerView.addItemDecoration(new LibraryTwoSpacesItemDecoration(height));
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (newState==0) {
//                    Fresco.getImagePipeline().resume();
//                } else {
//                    Fresco.getImagePipeline().pause();
//                }
//            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                listener.OnScroll(1, totalDy, dy);
            }
        });

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity()!=null && isVisibleToUser && viewBeans.size()==0) {
            updataUi(play_type_info, banner_ad);
        }
        if (!isVisibleToUser) {
            stopBannerPo();
        } else {
            initBannerPo();
        }
    }

    public void stopBannerPo() {
        if (layoutManager==null) return;
        View view = layoutManager.findViewByPosition(0);
        if (view==null) return;
        ConvenientBanner vp_recommend = view.findViewById(R.id.vp_recommend);
        if (vp_recommend!=null) {
            vp_recommend.stopTurning();
        }
    }

    public void initBannerPo() {
        if (layoutManager==null) return;
        View view = layoutManager.findViewByPosition(0);
        if (view==null) return;
        ConvenientBanner vp_recommend = view.findViewById(R.id.vp_recommend);
        if (vp_recommend!=null) {
            vp_recommend.setCurrentItem(MyApplication.bannerPo, false);
            vp_recommend.startTurning(4000-(System.currentTimeMillis() - MyApplication.bannerTime));
        }
    }

    public void onRefresh(final RefreshLayout refreshLayout) {
        getIndexDataForFirst();
    }

    public void onLoadMore(final RefreshLayout refreshLayout) {
        if (pn == 1) pn += 1;
        getIndexData();
    }

    private void getIndexDataForFirst() {
        refreshLayout.setEnableLoadMore(true);
        pn = 1;
        getIndexData();
    }

    private void getIndexData() {
        int uId = 0;
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean != null) {
            uId = AccountUtil.getInstance().getUid();
        }

        api.getGameLibraryV3(uId, pn, pn == 1 ? 0 : 2).enqueue(new MyCallback<ResponseBase<GameLibraryV3Response>>() {
            @Override
            public void onSuccess(ResponseBase<GameLibraryV3Response> model) {
                GameLibraryV3Response data = model.getData_info();
                if (data != null) {
                    updataUi(data.getPlay_type_info(), data.getBanner_ad());
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                refreshLayout.finishLoadMore();
            }
        });
    }

    private int insetPo = 0;
    private int itemPo = 0;
    private void updataUi(GameLibraryV3Response.PlayTypeInfoBean data, JumpBaseBean banner_ad) {
        if (data == null) {
            return;
        }
        int po = 0;
        if (pn == 1) {
            viewBeans.clear();

            if (banner!=null && banner.size()>0) {
                viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_TOP_HEIGHT1, banner));
            }
            viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_TOP_HEIGHT2));
            if (banner_ad!=null)
                viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_TOP_HEIGHT4, banner_ad));
            viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_TOP_HEIGHT3));
            viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_LINE));
            insetPo = viewBeans.size();
        } else {
            po = viewBeans.size();
        }

        List<GameLibraryV3Response.ListBean> tempList = data.getList();
//        for (int i = 0; tempList != null && i < tempList.size(); i++, itemPo++) {
//            GameLibraryV3Response.ListBean temp = tempList.get(i);
//            GameLibraryTwoAdapter.ViewBean viewBean = new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_ITEM, temp, itemPo);
//            viewBeans.add(insetPo+i, viewBean);
//        }
        List<GameLibraryV3Response.ListBean> temp = new ArrayList<>();
        for (int i = 0, itemPo = 0; tempList != null && i < tempList.size(); i++) {
            temp.add(tempList.get(i));
            if (temp.size()>=3) {
                List<GameLibraryV3Response.ListBean> list = new ArrayList<>();
                list.addAll(temp);
                GameLibraryTwoAdapter.ViewBean viewBean = new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_ITEM_V2, list);
                viewBeans.add(insetPo+itemPo, viewBean);
                itemPo++;
                temp.clear();
            }
        }

        insetPo = viewBeans.size();
        if (pn == 1) {
            viewBeans.add(new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_LINE));
        }
        if (pn == 1) {
            GameLibraryTwoAdapter.ViewBean viewBean = new GameLibraryTwoAdapter.ViewBean(GameLibraryTwoAdapter.ViewType.TYPE_BOTTOM, data.getBanner());
            viewBeans.add(viewBean);
        }

        adapter.notifyItemRangeChanged(po, viewBeans.size());
        if (refreshLayout != null) {
            if (pn != 1 && (data == null || data.getList() == null
                    || data.getList().size() == 0)) {
//                refreshLayout.finishLoadMore(300);
//                showToast("╮(๑•́ ₃•̀๑)╭下面~下面~没有了~", 500);
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public void onEventMainThread(DownloadEvent downloadEvent) {

    }
}
